const express = require('express');
const fetch = require('node-fetch');

const app = express();
const port = process.env.PORT || 3000;

// 设置代理路由
app.use('/proxy', async (req, res) => {
  try {
    const url = req.query.url;
    const response = await fetch(url, {
      method: req.method,
      headers: req.headers,
      body: req.method === 'GET' ? undefined : req.body,
    });

    const data = await response.text();

    // 设置响应头以允许跨域请求
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');

    res.send(data);
  } catch (error) {
    console.error(error);
    res.status(500).send('代理请求失败');
  }
});

// 启动代理服务器
app.listen(port, () => {
  console.log(`代理服务器正在运行，监听端口 ${port}`);
});
